package com.xgr.wonderful.utils;

import android.content.Context;
import com.google.gson.Gson;
import com.xgr.wonderful.entity.Photo;
import com.xgr.wonderful.entity.User;

public class LocalUserUtils {

	private static LocalUserUtils singletonLocalUserUtils;
	private User localUser = null;

	private LocalUserUtils() {
	}

	public static synchronized LocalUserUtils getInstance() {
		if (singletonLocalUserUtils == null) {
			singletonLocalUserUtils = new LocalUserUtils();
		}
		return singletonLocalUserUtils;
	}

	public void init(Context context) {
		if (localUser != null) {
			return;
		}
		localUser = SettingUtils.GetUserFromJson(context);
	}
	
	public User getLocalUser() {
		return localUser != null ? localUser : null;
	}	

	public String getLocalUserToken() {
		return localUser != null ? localUser.getToken() : null;
	}

	public Integer getLocalUserID() {
		return localUser != null ? localUser.getID() : null;
	}

	public String getLocalUserName() {
		return localUser != null ? localUser.getUsername() : null;
	}

	public String getLocalUserDeviceID() {
		return localUser != null ? localUser.getDeviceID() : null;
	}

	public Photo getLocalUserPhoto() {
		return localUser != null ? localUser.getPhoto() : null;
	}
	
	public String getLocalUserJson() {
		String jsonstr = null;
		try {
			jsonstr = new Gson().toJson(localUser);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return jsonstr;
	}

	/**
	 * 最好的是有这个后就保存到本地
	 * @param user
	 */
	public void saveLocalUser(User user) {
		if (user != null) {
			if (localUser == null) {
				localUser = new User();
			}
			localUser = user;
		}
	}

	// 将内存中的本地用户对象序列化到磁盘上
	// 每次程序退出的时候调用一次即可
	public void saveLocalUser(Context context) {
		if (localUser != null)
			try {
				SettingUtils
						.SaveUserJson(context, new Gson().toJson(localUser));
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
	}
	
	/**
	 * 保存到内存中后，就执行保存到磁盘
	 * @param context
	 * @param user
	 */
	public void saveLocalUser (Context context, User user){
		if (user != null) {
			if (localUser == null) {
				localUser = new User();
			}
			localUser = user;
		}
		try {
			SettingUtils
					.SaveUserJson(context, new Gson().toJson(localUser));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	


}
